<template>
    <div class="AccountList">
        <div>
            <branch-tree :height="bodySize.height - subAuthTree" @change="branchChange"></branch-tree>
        </div>
        <div>
            <div class="page-action-btn" v-if="!select">
                <el-button type="primary" v-if="UIAuth._api_admin_account_post" @click="showAdd">添加</el-button>
                <el-button type="warning" v-if="UIAuth._api_admin_account_put" @click="showEdit">修改</el-button>
                <p-confirm-btn @confirm="del" v-if="UIAuth._api_admin_account_delete"></p-confirm-btn>
            </div>
            <div v-if="UIAuth._api_admin_account_paginate_get">
                <p-table ref="pTable" v-loading="loading" :data="dataList" :sub-height="subHeight" :show-paginate="true" v-model="paginate" @row-click="rowClick" @row-dblclick="dblClick"
                    @row-clear="rowClear" @selection-change="selectionChange" @paginate="getList">
                    <el-table-column prop="nickname" label="昵称" width="200"></el-table-column>
                    <el-table-column prop="account" label="账号" min-width="160"></el-table-column>
                    <el-table-column prop="account_type" label="账号类型" width="95">
                        <template v-slot="{ row }">
                            <user-type :type="row.account_type"></user-type>
                        </template>
                    </el-table-column>
                    <el-table-column prop="username" label="姓名" width="80"></el-table-column>
                    <el-table-column prop="id_card" label="身份证号码" width="170"></el-table-column>
                    <el-table-column prop="mobile" label="手机" width="120"></el-table-column>
                    <el-table-column prop="account.sex" label="性别" width="50">
                        <template v-slot="{ row }">
                            <sex :sex="row.sex"></sex>
                        </template>
                    </el-table-column>
                    <el-table-column prop="post" label="职位/岗位" min-width="120"></el-table-column>
                    <el-table-column prop="province" label="省份" min-width="120"></el-table-column>
                    <el-table-column prop="city" label="城市" min-width="120"></el-table-column>
                    <el-table-column prop="created" label="创建时间" width="160">
                        <template v-slot="{ row }">
                            <div>{{ utils.GolangDateTime(row.created) }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="desc" label="备注" min-width="360"></el-table-column>
                </p-table>
            </div>
            <p-el-dialog v-if="!select" v-model="showDialog" :title="`${isEdit ? '修改' : '添加'}用户账号`" width="40%" :height="bodySize.height - 130" @close="dialogClose" @confirm="isEdit ? edit() : add()"
                :ok-text="isEdit ? '修改' : '添加'">
                <el-form :model="params" status-icon :rules="paramsRules" ref="elForm" label-width="120px">
                    <el-form-item label="账号类型">
                        <el-select v-model="params.account_type" placeholder="请选择账号类型">
                            <el-option v-for="(item,key) in accountTypeArray" :key="key" :label="item.label" :value="item.val"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="所属部门机构">
                        <branch-tree-select v-model="params.bid"></branch-tree-select>
                    </el-form-item>

                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model="params.nickname" placeholder="请输入昵称"></el-input>
                    </el-form-item>

                    <el-form-item label="账号" prop="account">
                        <el-input v-model="params.account" placeholder="请输入账号"></el-input>
                    </el-form-item>
                    <el-form-item label="登陆密码">
                        <el-input type="password" v-model="params.password" placeholder="请输入登陆密码"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码">
                        <el-input type="password" v-model="params.passwordok" placeholder="请输再次入登陆密码"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名">
                        <el-input v-model="params.username" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="身份证号码">
                        <el-input v-model="params.id_card" placeholder="请输入身份证号码"></el-input>
                    </el-form-item>
                    <el-form-item label="手机">
                        <el-input v-model="params.mobile" placeholder="请输入手机"></el-input>
                    </el-form-item>
                    <el-form-item label="职位/岗位">
                        <el-input v-model="params.post" placeholder="请输入职位/岗位"></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-select v-model="params.sex" placeholder="请选择性别">
                            <el-option label="男" :value="1"></el-option>
                            <el-option label="女" :value="2"></el-option>
                            <el-option label="未知" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="省份">
                        <el-input v-model="params.province" placeholder="请输入省份"></el-input>
                    </el-form-item>
                    <el-form-item label="城市">
                        <el-input v-model="params.city" placeholder="请输入城市"></el-input>
                    </el-form-item>
                    <el-form-item label="简介">
                        <el-input v-model="params.explain" type="textarea" :row="5" placeholder="请输入简介"></el-input>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input type="textarea" :row="5" v-model="params.desc" placeholder="请输入备注"></el-input>
                    </el-form-item>
                </el-form>
            </p-el-dialog>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs, onMounted } from "vue";
import { useStore } from "vuex";
import BranchTree from "@/components/branch/BranchTree.vue";
import { IPaginate, defaultPaginate } from "@/lib/IApp";
import PTable from "@/components/PTable.vue";
import PElDialog from "@/components/PElDialog.vue";
import http from "@/lib/http/http";
import PConfirmBtn from "@/components/PConfirmBtn.vue";
import UserType from "@/components/user/UserType.vue";
import BranchTreeSelect from "@/components/branch/BranchTreeSelect.vue";
import message from "@/lib/message";
import utils from "@/lib/utils";
import Sex from "@/components/Sex.vue";
import md5 from "js-md5";
import storage from "@/lib/storage/storage";
import AccountType, { AccountTypeArray } from "../../lib/user/AccountType";
// 参数校验
const ParamsRules: any = {
    nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
    account: [
        {
            trigger: "blur",
            validator: (rule: any, value: string, callback: any) => {
                // rule 对应使用bargainMoney自定义验证的 对象
                // value 对应使用bargainMoney自定义验证的 数值
                // callback 回调函数
                if (utils.empty(value)) {
                    callback(new Error("账号不能为空"));
                } else if (value !== "root" && value.length < 5) {
                    callback(new Error("账号最少5位"));
                } else {
                    callback();
                }
            },
        },
    ],
};
/**
 * state 数据类型
 */
interface IState {
    loading: boolean;
    /**
     * 分页数据
     */
    paginate: IPaginate;
    /**
     * 获取到的数据列表
     */
    dataList: any[];
    /**
     * 是否显示 添加编辑窗口
     */
    showDialog: boolean;
    /**
     * 是否修改
     */
    isEdit: boolean;
    /**
     * http 请求参数
     */
    params: any;
    /**
     * 单选选择的行内容
     */
    tableRow: any;
    /**
     * 多选选择的行内容
     */
    tableRows: any[];
    /**
     * 搜索条件
     */
    search: any;
    /**
     * 用户信息
     */
    user: any;
    /**
     * 登陆用户权限类型
     */
    account_type: number;
    /**
     * 账号类型数组
     */
    accountTypeArray: any[];
}
export default defineComponent({
    name: "AccountList",
    components: {
        BranchTree,
        PTable,
        PElDialog,
        PConfirmBtn,
        UserType,
        BranchTreeSelect,
        Sex,
    },
    props: {
        subHeight: {
            type: Number,
            default: 0,
        },
        subAuthTree: {
            type: Number,
            default: 0,
        },
        select: {
            type: Boolean,
            default: false,
        },
    },
    emits: ["change", "dblclick", "dataList"],
    setup(props, { emit }) {
        const store = useStore();
        const { UIAuth, bodySize } = toRefs(store.state);
        /**
         * el 表格元素
         */
        const pTable = ref<any>(null);
        /**
         * el 表单元素
         */
        const elForm = ref<any>(null);
        const state = reactive<IState>({
            loading: false,
            paginate: defaultPaginate,
            dataList: [],
            showDialog: false,
            isEdit: false,
            params: {},
            tableRow: null,
            tableRows: [],
            search: { bid: "" },
            user: {},
            account_type: 0,
            accountTypeArray: [],
        });
        /**
         * 单击选中
         */
        const rowClick = (val: any) => {
            state.tableRow = val.row;
            if (props.select) {
                emit("change", val.row);
            }
        };
        /**
         * 取消选中
         */
        const rowClear = () => {
            state.tableRow = null;
            if (props.select) {
                emit("change", null);
            }
        };
        /**
         * 关闭添加修改窗口
         */
        const dialogClose = () => {
            state.params = {};
            state.isEdit = false;
            state.showDialog = false;
        };
        /**
         * 多选时触发
         */
        const selectionChange = (val: any[]): void => {
            state.tableRows = val;
        };
        /**
         * 显示添加
         */
        const showAdd = () => {
            state.params = {};
            state.isEdit = false;
            state.showDialog = true;
        };
        /**
         * 获取内容
         */
        const getList = () => {
            state.loading = true;
            state.dataList = [];
            http.Get(
                `/account/${state.paginate.page_size}/${state.paginate.page}`,
                state.search
            )
                .then((data) => {
                    state.dataList = data.data;
                    state.paginate = data.paginate;
                    state.loading = false;
                    emit("dataList", data.data);
                })
                .catch((err) => (state.loading = false));
        };
        /**
         * 部门机构选择事件
         */
        const branchChange = (row: any) => {
            // console.log(row);
            if (row == null) {
                state.search.bid = "";
            } else {
                state.search.bid = row.id;
            }
            state.tableRow = null;
            state.tableRows = [];
            pTable.value.clearSelect();
            getList();
        };

        /**
         * 添加
         */
        const add = () => {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    const params = utils.CopyNewObject(state.params);
                    if (!utils.empty(params.password)) {
                        if (params.password !== params.passwordok) {
                            message.error("两次输入的登陆密码不一致");
                            return false;
                        }
                        params.passwordok = "";
                        params.password = md5(params.password);
                    }
                    http.Post("/account", params)
                        .then((data) => {
                            if (utils.empty(state.dataList)) {
                                state.dataList = [data];
                            } else {
                                state.dataList.unshift(data);
                            }
                            state.params = {};
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        };
        /**
         * 显示修改
         */
        const showEdit = () => {
            if (state.tableRow == null) {
                message.error("请选择要修改的账号");
                return;
            }
            state.isEdit = true;

            state.params.bid = state.tableRow.bid;
            state.params.account_type = state.tableRow.account_type;
            state.params.account = state.tableRow.account;
            state.params.post = state.tableRow.post;
            state.params.explain = state.tableRow.explain;
            state.params.mobile = state.tableRow.mobile;
            state.params.id_card = state.tableRow.id_card;
            state.params.username = state.tableRow.username;
            state.params.email = state.tableRow.email;
            state.params.nickname = state.tableRow.nickname;
            state.params.sex = state.tableRow.sex;
            state.params.avatar_url = state.tableRow.avatar_url;
            state.params.province = state.tableRow.province;
            state.params.city = state.tableRow.city;
            state.params.desc = state.tableRow.desc;

            state.params.id = state.tableRow.id;
            state.params.aid = state.tableRow.aid;
            state.params.version = state.tableRow.version;
            state.showDialog = true;
        };
        /**
         * 双击选择
         */
        const dblClick = (val: any) => {
            if (props.select) {
                emit("dblclick", val.row);
            } else {
                showEdit();
            }
        };
        /**
         * 修改
         */
        const edit = () => {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    const params = utils.CopyNewObject(state.params);
                    if (!utils.empty(params.password)) {
                        if (params.password !== params.passwordok) {
                            message.error("两次输入的登陆密码不一致");
                            return false;
                        }
                        params.passwordok = "";
                        params.password = md5(params.password);
                    }
                    http.Put("/account", params)
                        .then((data) => {
                            const index = state.dataList.findIndex(
                                (item) => item.id === state.tableRow.id
                            );
                            if (index >= 0) {
                                state.dataList.splice(index, 1, data);
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        };
        /**
         * 删除
         */
        const del = () => {
            const ids: string[] = [];
            if (state.tableRows.length === 0) {
                if (state.tableRow == null) {
                    message.error("请选择要删除的账号");
                    return;
                } else {
                    ids.push(state.tableRow.id);
                }
            }
            state.tableRows.forEach((item) => {
                ids.push(item.id);
            });
            message.loadingShow("删除中");
            http.Delete("/account", { ids })
                .then((data) => {
                    ids.forEach((id) => {
                        const index = state.dataList.findIndex(
                            (item) => item.id === id
                        );
                        if (index >= 0) {
                            state.dataList.splice(index, 1);
                        }
                        state.tableRows = [];
                    });
                })
                .catch((err) => "");
        };
        onMounted(() => {
            state.user = storage.user.Get();
            state.account_type = state.user.account.account_type;
            if (state.account_type === AccountType.SYSTEM_ADMIN) {
                state.accountTypeArray = AccountTypeArray;
            } else {
                AccountTypeArray.forEach((item: any) => {
                    if (item.val < state.account_type) {
                        state.accountTypeArray.push(item);
                    }
                });
            }
            getList();
        });
        return {
            UIAuth,
            bodySize,
            ...toRefs(state),
            paramsRules: ParamsRules,
            elForm,
            pTable,
            rowClick,
            dblClick,
            rowClear,
            showAdd,
            branchChange,
            getList,
            add,
            showEdit,
            edit,
            del,
            utils,
            selectionChange,
            dialogClose,
        };
    },
});
</script>

<style scoped lang="scss">
.AccountList {
    display: flex;
    justify-content: space-between;
    & > div {
        &:first-child {
            width: 240px;
        }
        &:last-child {
            width: calc(100% - 250px);
        }
    }
}
</style>